package com.opesoft.pf.hibernate;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateSession
{
	Logger log=Logger.getLogger(this.getClass());

	Session se; // 用于产生Transaction的Session
	int level=-1; // 打开事务时所在的层次
	Transaction transaction; // 打开的Transaction

	public HibernateSession(Session se)
	{
		this.se=se;
	}

	public Session getSession()
	{
		return this.se;
	}

	public void beginTransaction()
	{
		if(this.level<0)
		{
			this.transaction=this.se.beginTransaction();
			this.level=Thread.currentThread().getStackTrace().length;
			log.debug("Begin Transaction.");
		}
	}

	public void commitTransaction(boolean commit)
	{
		if(this.level==Thread.currentThread().getStackTrace().length)
		{
			if(commit)
			{
				this.transaction.commit();
				log.debug("Commit Transaction.");
			}
			else
			{
				this.transaction.rollback();
				log.debug("Rollback Transacton.");
			}

			this.transaction=null;
			this.level=-1;
		}
	}

}
